import io from 'socket.io-client'
import Store from '../../index'

class SocketClient {

  /**
   * 构造函数
   * @param uri 默认为window.location
   * @param opts https://github.com/socketio/socket.io-client/blob/HEAD/docs/API.md#new-managerurl-options
   */
  constructor() {

    this.socket = io('/chat', {
      query: {
        room: 'WEB'
      }
    });

    this.socket.on('connect', this.connect)
    this.socket.on('disconnect', this.disconnect)
    this.socket.on('currentSocket', this.currentSocket)
    this.socket.on('numberChange', this.numberChange)
    this.socket.on('message', this.message)
  }

  /**
   * 连接成功的回调
   */
  connect() {
    console.log('connect')
  }

  /**
   * 断开连接的回调
   */
  disconnect() {
    console.log('disconnect')
  }

  /**
   * 获取当前socket id
   * @param data 获取的数据
   */
  currentSocket(data) {
    Store.commit('SET_CURRENT_CLIENT_ID', data.current)
  }

  /**
   * 聊天人数改变的时候调用
   * @param data
   */
  numberChange(data) {
    Store.commit('SET_SOCKET_CLIENTS', data)
  }

  /**
   * 接收到数据
   */
  message(data) {
    Store.commit('ADD_MESSAGE', data)
    Store.commit('SET_UNREAD_COUNT', true)
  }
}

export default SocketClient
